package com.cci.kangdao.dao;

import com.cci.kangdao.dao.model.RolesT;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.mybatis.spring.annotation.MapperScan;

import java.util.List;
import java.util.Map;


/**
 * 角色表dao
 *
 */
@MapperScan
public interface RolesTDao {

	//根据ID获取这个用户所有岗位信息(这个人的岗位信息可能不止一条)
	@Select("select a.* from Roles_T a\r\n" +
			"inner join UserGroupHasRole_T b on a.ID =b.RoleId\r\n" +
			"inner join UserHasRoles_T c on b.ID = c.RolesID\r\n" +
			"inner join User_T d on c.UserID = d.ID\r\n" +
			"where d.ID=#{UserID} and a.Flag=0 and b.Flag=0 and c.Flag=0 and d.Flag=0")
	public List<RolesT> getRoleListByUserID(Long userId);

	@Select("select * from Roles_T where ID = #{roleId}")
	RolesT getRolesById(Long roleId);

	@Select("select ughr.ID from UserGroupHasRole_T ughr " +
			"inner join Roles_T roles on ughr.RoleId = roles.ID and ughr.Flag = 0 and roles.Flag = 0 " +
			"where ughr.UserGroupId = #{userGroupId} and roles.RolesNo = #{rolesNo}")
	List<Long> getUserGroupHasRolesIdList(@Param("userGroupId") Long userGroupId,@Param("rolesNo") String rolesNo);


	@Select(" select * from (\n" +
			"\tSELECT distinct UserId,\n" +
			"\tSTUFF(( SELECT  ',' + SURS.RolesName\n" +
			"\t\tFROM   (select UR.UserID UserId,R.RolesName RolesName from Roles_T R,UserHasRoles_T UR,UserGroupHasRole_T UGR  where R.Flag = 0 and UR.Flag = 0 and UGR.Flag = 0 and UR.RolesID = UGR.ID and UGR.RoleId = R.ID) SURS\n" +
			"\t\tWHERE   SURS.UserId = IURS.UserId FOR XML PATH('')), 1, 1, '') AS RoleNames\n" +
			"\t\tFROM  (select UR.UserID UserId from Roles_T R,UserHasRoles_T UR,UserGroupHasRole_T UGR  where R.Flag = 0 and UR.Flag = 0 and UGR.Flag = 0 and UR.RolesID = UGR.ID and UGR.RoleId = R.ID) IURS\n" +
			") URS\n" +
			"WHERE URS.UserId = #{userId}")
	Map<String,Object> getRoleNamesByUserId(@Param("userId")long userId);

	@Select("select * from Roles_T where Flag =0 and RolesNo = #{roleNo}")
	Map<String,Object> getRoleByRoleNo(@Param("roleNo")String roleNo);


	/**
	 * 根据微信ID查询是否有某角色权限
	 * @param openId  微信ID
	 * @param companyID  渠道ID
	 * @param role		角色编码
	 * @return 0是无权限1是有权限
	 */
	@Select("select count(a.ID) from Roles_T a " +
			"inner join UserGroupHasRole_T b on a.ID =b.RoleId " +
			"inner join UserHasRoles_T c on b.ID = c.RolesID " +
			"inner join WeChatUserRelation_T d on c.UserID = d.UserID " +
			"inner join User_T UT on UT.ID = d.UserID " +
			"where d.OpenID=#{openId} and d.CompanyID=#{companyID} and a.RolesNo = #{role} and UT.ID = #{userId} and UT.Flag=0 and a.Flag=0 and b.Flag=0 and c.Flag=0 and d.Flag=0")
	Integer getRoleNumByOpenID(@Param("userId")Long userId,@Param("openId") String openId,@Param("companyID") Long companyID,@Param("role")String role);

}
